package icu.feigroup.domain.trade.service.locak.filter;

import icu.feigroup.domain.trade.adapter.repository.ITradeRepository;
import icu.feigroup.domain.trade.model.entity.GroupBuyActivityEntity;
import icu.feigroup.domain.trade.model.entity.TradeLockRuleCommandEntity;
import icu.feigroup.domain.trade.model.entity.TradeLockRuleFilterBackEntity;
import icu.feigroup.domain.trade.service.locak.factory.TradeLockRuleFilterFactory;
import icu.feigroup.types.design.framwork.link.model2.handler.ILogicHandler;
import icu.feigroup.types.enums.ActivityStatusEnumVO;
import icu.feigroup.types.enums.ResponseCode;
import icu.feigroup.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * projectName:icu.feigroup.domain.trade.service.locak.filter
 *
 * @author 飞
 * @since 2025/2/25 16:06
 * description:活动的可用性，规则过滤【状态、有效期】
 */
@Slf4j
@Service
public class ActivityUsabilityRuleFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {
    @Resource
    private ITradeRepository repository;
    @Override
    public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-活动的可用性校验{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());
        GroupBuyActivityEntity groupBuyActivityEntity = repository.queryGroupBuyActivityByActivityId(requestParameter.getActivityId());
        if (!ActivityStatusEnumVO.EFFECTIVE.equals(groupBuyActivityEntity.getStatus())){
            throw new AppException(ResponseCode.E101);
        }
        Date currentDate = new Date();
        if (currentDate.before(groupBuyActivityEntity.getStartTime())|| currentDate.after(groupBuyActivityEntity.getEndTime())){
            throw new AppException(ResponseCode.E102);
        }
        dynamicContext.setGroupBuyActivityEntity(groupBuyActivityEntity);
        return next(requestParameter,dynamicContext);
    }
}
